/**
 * Created by huotaol on 2017/4/27.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {Image, StyleSheet, Text, TouchableOpacity, TouchableWithoutFeedback, View} from "react-native";
import {connect} from "react-redux";
import SaleHeader from "../../components/SaleHeader";
import BuyCarFilterTabBar from "../../components/BuyCarFilterTabBar";
import CustomStyle from "../../../common/style/CustomStyle";
import {Actions} from "react-native-router-flux";
import * as Url from "../../constant/Url";
import {request} from "../../../common/util/RequestUtil";
import * as BuyCarAction from "../../redux/action/BuyCar";
import * as ActionTypeConstant from "../../constant/ActionType";
import Modal from "react-native-modal";
import Order from "./Order";
import Price from "./Price";
import CarList from "./component/CarList";
import {initFilterParam} from "../../redux/reducer/BuyCar";
import * as homePageAction from "../../redux/action/homePage";
import PubSub from "pubsub-js";

class BuyCar extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {orderVisible: false, priceVisible: false,};
        this._refresh = this._refresh.bind(this);
        this._renderFilter = this._renderFilter.bind(this);
        this._onCarDetailSelected = this._onCarDetailSelected.bind(this);
    }

    componentWillMount() {
        PubSub.subscribe(ActionTypeConstant.BUY_CAR_FILTER_REFRESH, this._refresh);
    }

    componentDidMount() {
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this._refresh);
    }

    render() {
        const filterTitleList = [];
        filterTitleList.push({name: '品牌', click: () => Actions.BrandRoot({onSelected: this._onCarDetailSelected})});
        filterTitleList.push({
            name: '排序', click: () => this.setState({orderVisible: true})
        })
        ;
        filterTitleList.push({name: '价格', click: () => this.setState({priceVisible: true})});
        filterTitleList.push({name: '筛选', click: () => Actions.Filter()});

        return (
            <View style={{flex: 1}}>
                <SaleHeader/>
                <BuyCarFilterTabBar titleList={filterTitleList}
                                    renderItem={this._renderItem}
                />
                {this._renderFilter()}
                <CarList
                    ref="carlist"
                    onFetch={this._onFetch.bind(this)}
                    firstLoader={true} // display a loader for the first fetching
                    pagination={true} // enable infinite scrolling using touch to load more
                    refreshable={false} // enable pull-to-refresh for iOS and touch-to-refresh for Android
                />
                <TouchableWithoutFeedback onPress={() => {
                    this.setState({orderVisible: false});
                }}>
                    <Modal isVisible={this.state.orderVisible}
                           animationIn='slideInDown'
                           animationOut='slideOutUp'
                           style={{margin: 0,}}
                    >
                        <Order
                            confirm={() => {
                                this.setState({orderVisible: false});
                            }}/>
                    </Modal>
                </TouchableWithoutFeedback>

                <TouchableWithoutFeedback onPress={() => {
                    this.setState({priceVisible: false});
                }}>
                    <Modal isVisible={this.state.priceVisible}
                           animationIn='slideInDown'
                           animationOut='slideOutUp'
                           style={{margin: 0, justifyContent: 'flex-start',}}
                    >
                        <Price
                            confirm={() => {
                                this.setState({priceVisible: false});
                            }}/>
                    </Modal>
                </TouchableWithoutFeedback>

            </View>
        );
    }

    _onFetch(page = 1, options) {
        const url = Url.BASE_URL + '/jishou/get_cars_json';
        console.log(Url.BASE_URL);
        const locationID = this.props.selectArea.id;
        const param = processFilter(locationID, this.props.filter, page === 1);
        return new Promise(resolve => {
            request(url, 'POST', param)
                .then(json => {
                    console.log(json);
                    const data = json.data;
                    const imgPrefix = data.imgPrefix;
                    const begin = data.begin;
                    const total = data.total;
                    const list = data.list;
                    this.props.updateFilter({
                        begin,
                        total,
                    });
                    const row = list.map(item => Object.assign({}, item, {imgName: imgPrefix + item.imgName}));
                    resolve({data: row, finish: total <= 0});
                });
        });
    }

    _refresh() {
        this.refs.carlist._refresh();
    }

    _renderItem(item, index) {
        return <Item title={item.name} click={item.click} key={index}/>;
    }


    _renderFilter() {
        const {filter} = this.props;
        const filterList = [];
        const {brand, series, keyword, kind, gearbox, emission, price, meter, year, displacement} = filter;
        let render = false;
        if (brand) {
            render = true;
            filterList.push(<FilterItem content={brand} click={() => {
                this.props.updateFilter({brand: '', series: ''});
                refreshBuyCarFilter();
            }}/>);
        }
        if (series) {
            render = true;
            filterList.push(<FilterItem content={series} click={() => {
                this.props.updateFilter({series: ''});
                refreshBuyCarFilter();
            }}/>);
        }

        if (keyword) {
            render = true;
            filterList.push(<FilterItem content={keyword} click={() => {
                this.props.updateFilter({keyword: ''});
                refreshBuyCarFilter();
            }}/>);
        }

        if (kind.length) {
            render = true;
            kind.map(item => {
                filterList.push(<FilterItem content={item} click={() => {
                    kind.splice(kind.indexOf(item), 1);
                    refreshBuyCarFilter({kind});
                }}/>);
            });
        }

        if (emission.length) {
            render = true;
            emission.map(item => {
                filterList.push(<FilterItem content={item} click={() => {
                    emission.splice(emission.indexOf(item), 1);
                    refreshBuyCarFilter({emission});
                }}/>);
            });
        }

        if (gearbox) {
            render = true;
            filterList.push(<FilterItem content={gearbox} click={() => {
                this.props.updateFilter({gearbox: ''});
                refreshBuyCarFilter();
            }}/>);
        }

        const defaultParam = {from: 0, to: '∞'};

        if (price && (parseInt(price.from) > 0 || parseInt(price.to))) {
            render = true;
            filterList.push(<FilterItem content={getLimitContent(price, '万')} click={() => {
                this.props.updateFilter({price: defaultParam});
                refreshBuyCarFilter();
            }}/>);
        }

        if (meter && (parseInt(meter.from) > 0 || parseInt(meter.to))) {
            render = true;
            filterList.push(<FilterItem content={getLimitContent(meter, '万公里')} click={() => {
                this.props.updateFilter({meter: defaultParam});
                refreshBuyCarFilter();
            }}/>);
        }

        if (displacement && (parseInt(displacement.from) > 0 || parseInt(displacement.to))) {
            render = true;
            filterList.push(<FilterItem content={getLimitContent(displacement, 'L')} click={() => {
                this.props.updateFilter({displacement: defaultParam});
                refreshBuyCarFilter();
            }}/>);
        }
        if (render) {
            return <View style={{
                flexDirection: 'row', backgroundColor: '#FFFCEE',
                paddingLeft: CustomStyle.getActualSizeInHorizontal(30),
                paddingRight: CustomStyle.getActualSizeInHorizontal(30),
                paddingBottom: CustomStyle.getActualSizeInVertical(16),
            }}>
                <View style={{flexDirection: 'row', flexWrap: 'wrap', flex: 1,}}>
                    {filterList}
                </View>
                <TouchableOpacity
                    onPress={() => {
                        this.props.updateFilter({...initFilterParam});
                        refreshBuyCarFilter();
                    }}
                    style={{flexDirection: 'row', alignItems: 'center',}}>
                    <Image source={require('../../../img/buyCar/refresh.png')}
                           resizeMode={'contain'}
                           style={{
                               width: CustomStyle.getActualSizeInHorizontal(28),
                               height: CustomStyle.getActualSizeInVertical(26),
                           }}/>
                    <Text
                        style={[CustomStyle.baseText, styles.filterText, {marginLeft: CustomStyle.getActualSizeInHorizontal(30),}]}>重置</Text>
                </TouchableOpacity>
            </View>
        }
    }

    _onCarDetailSelected(brand, series, kind) {
        this.props.updateFilter({begin: 0, total: 0, brand: brand, series: series, keyword: '',});
        refreshBuyCarFilter();
    }

}


class Item extends Component {
    static propTypes = {
        title: PropTypes.string,
        select: PropTypes.bool,
        click: PropTypes.func,
    };

    _renderUnderLine(show) {
        if (show) {
            return <View style={{
                height: CustomStyle.getActualSizeInVertical(5),
                backgroundColor: '#ffc000',
            }}>
            </View>
        }
    }

    render() {
        const arrowDown = require('../../../img/buyCar/arrow_down.png');
        const arrowUp = require('../../../img/buyCar/arrow_up.png');
        const selected = this.props.select;
        return (
            <TouchableOpacity onPress={this.props.click}
                              style={{
                                  flex: 1,
                                  flexDirection: 'row',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                              }}>
                <Text
                    style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(30),
                        color: selected ? '#ffc000' : '#8c7a44',
                    }]}>{this.props.title}</Text>
                <Image source={selected ? arrowDown : arrowUp}
                       style={{
                           width: CustomStyle.getActualSizeInHorizontal(20),
                           height: CustomStyle.getActualSizeInVertical(10),
                       }}
                />
                {this._renderUnderLine(selected)}
            </TouchableOpacity>
        );
    }
}

class FilterItem extends Component {
    static propTypes = {
        content: PropTypes.string,
        click: PropTypes.func,
    };

    render() {
        console.log('FilterItem render ' + this.props.content);
        return (
            <TouchableOpacity
                onPress={this.props.click}
                style={{
                    height: CustomStyle.getActualSizeInVertical(58),
                    paddingLeft: CustomStyle.getActualSizeInHorizontal(8),
                    minWidth: CustomStyle.getActualSizeInHorizontal(140),
                    paddingRight: CustomStyle.getActualSizeInHorizontal(8),
                    paddingTop: CustomStyle.getActualSizeInVertical(8),
                    paddingBottom: CustomStyle.getActualSizeInVertical(8),
                    alignItems: "center",
                    justifyContent: 'center',
                    backgroundColor: 'white',
                    marginRight: CustomStyle.getActualSizeInHorizontal(20),
                    marginTop: CustomStyle.getActualSizeInVertical(16),
                }}>
                <Text
                    numberOfLines={1}
                    style={[CustomStyle.baseText, styles.filterText, {flex: 1}]}>{this.props.content}</Text>
            </TouchableOpacity>
        );
    }
}

const styles = StyleSheet.create({
    filterText: {
        fontSize: CustomStyle.getActualFontSize(28),
        color: '#857e6e',
    },
});

function processFilter(locationID, filter, isForceRefesh) {
    const param = new FormData();
    let begin = filter.begin;
    let total = filter.total;
    if (isForceRefesh === true) {
        begin = 0;
        total = 0;
    }
    param.append('begin', begin);
    param.append('max', filter.max);
    param.append('total', total);
    param.append('loc', locationID);
    param.append('brand', filter.brand);
    param.append('set', filter.series);
    param.append('keywords', filter.keyword);
    param.append('srctype', filter.origin);
    param.append('kind', filter.kind.join(','));
    param.append('geartype', filter.gearbox);
    param.append('emission', filter.emission.join(','));
    param.append('price', getLimit(filter.price));
    param.append('meter', getLimit(filter.meter));
    param.append('year', getLimit(filter.year));
    param.append('dp', getLimit(filter.displacement));
    param.append('sid', filter.shopID);
    param.append('sold', filter.sold);
    param.append('ordertype', filter.orderType);
    param.append('orderby', filter.orderBy);
    // console.log('proceFitler ' + JSON.stringify(param));
    return param;
}


const mapStateToProps = (state) => {
    const {buyCarFilter, selectArea} = state;
    const {area} = selectArea;
    return {
        filter: buyCarFilter,
        selectArea: area,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        updateFilter: param => dispatch(BuyCarAction.buyCarFilter(param)),
        setSelectArea: area => dispatch(homePageAction.setSelectArea(area)),
    }
};

function getLimitContent(param, unit) {
    let {from, to} = param;
    let content = from;
    to = parseInt(to);
    if (to) {
        content += ('-' + to + unit);
    } else {
        content += (unit + '以上');
    }
    return content;
}

export const refreshBuyCarFilter = () => {
    PubSub.publish(ActionTypeConstant.BUY_CAR_FILTER_REFRESH);
};

export function getLimit(param) {
    const {from = 0, to = '∞'} = param;
    return from + '-' + to;
}

export default connect(mapStateToProps, mapDispatchToProps)(BuyCar);
